package com.example.demo;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;
import com.alibaba.fastjson.JSON;

@RestController
@RequestMapping(value = "/redis_users")
public class RedisController {

    @Value("${app.configuration.redis.channel}")
    private String channel = "";
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    // redis中存储的过期时间60s
    private static int ExpireTime = 60;

    @GetMapping("/publish")
    public String publish(@RequestParam String message) {
        // 发送消息
        redisTemplate.convertAndSend(this.channel, message);
        return this.channel + ":" + message;
    }

    @PostMapping("/")
    public String redisSet(@Valid @RequestBody User user) {
        // @RequestBody注解用来绑定通过http请求中application/json类型上传的数据
        try {
            redisTemplate.opsForValue().set(user.getName(), JSON.toJSONString(user));
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "exception";
        }
    }

    @GetMapping("get")
    public Object redisGet(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    @GetMapping("expire")
    public boolean expire(String key) {
        try {
            if (ExpireTime > 0) {
                redisTemplate.expire(key, ExpireTime, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}